package com.aidex.biz.service.impl;

import com.aidex.biz.domain.*;
import com.aidex.biz.domain.bo.BusinessSetBo;
import com.aidex.biz.domain.enums.CustomerEnum;
import com.aidex.biz.domain.enums.DongTaiTypeEnum;
import com.aidex.biz.domain.enums.MessageTypeEnum;
import com.aidex.biz.domain.vo.CustomerExpertVo;
import com.aidex.biz.domain.vo.YuanGongGongziVo;
import com.aidex.biz.mapper.CustomerMapper;
import com.aidex.biz.mapper.TempShareMapper;
import com.aidex.biz.service.*;
import com.aidex.biz.utils.CityUtils;
import com.aidex.biz.utils.RongXiangKeAESUtil;
import com.aidex.biz.utils.TencentSmsUtils;
import com.aidex.common.annotation.DataScope;
import com.aidex.common.core.domain.entity.SysUser;
import com.aidex.common.core.page.PageDomain;
import com.aidex.common.core.redis.RedisCache;
import com.aidex.common.core.service.BaseServiceImpl;
import com.aidex.common.core.text.Convert;
import com.aidex.common.exception.CustomException;
import com.aidex.common.utils.NumberUtils;
import com.aidex.common.utils.SecurityUtils;
import com.aidex.common.utils.StringUtils;
import com.aidex.common.utils.http.HttpUtils;
import com.aidex.common.utils.sign.Md5Utils;
import com.aidex.common.utils.sql.SqlUtil;
import com.aidex.framework.cache.ConfigUtils;
import com.aidex.framework.websocket.WebSocketUsers;
import com.aidex.system.mapper.SysUserMapper;
import com.aidex.system.service.CompanyService;
import com.aidex.system.service.ISysUserService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.time.Instant;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 左心房客户推送信息Service业务层处理
 *
 * @author sean
 * @email 2074844820@qq.com
 * @date 2023-04-03
 */
@Service
@Transactional(readOnly = true)
public class CustomerServiceImpl extends BaseServiceImpl<CustomerMapper, Customer> implements CustomerService {
    private static final Logger log = LoggerFactory.getLogger(CustomerServiceImpl.class);
    final String secretKey = "11662107190";
    @Autowired
    ZhuangkuLogService zhuangkuLogService;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private TempShareService tempShareService;

    @Autowired
    private TempShareMapper tempShareMapper;
    @Autowired
    private ShareLogService shareLogService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private AccountLogService accountLogService;
    @Autowired
    private SmsLogService smsLogService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysUserService iSysUserService;

    @Autowired
    private CustomerDongtaiService customerDongtaiService;
    @Autowired
    private CustomerXiezuService customerXiezuService;
    @Autowired
    private XiezuService xiezuService;
    @Autowired
    private PushCustomerService pushCustomerService;
    @Autowired
    private MessageInfoService messageInfoService;
    @Autowired
    private RedisCache redisCache;
    private ShareLog shareLog;
    @Autowired
    private PushRuleUserService pushRuleUserService;
    @Autowired
    private XiansuoChengbenLogService xiansuoChengbenLogService;
    @Autowired
    private CustomerTagService customerTagService;
    @Autowired
    private CustomerReceiveService customerReceiveService;
    @Autowired
    private TempShareRuleService tempShareRuleService;
    @Autowired
    private CustomerShadowInfoServiceImpl customerShadowInfoService;
    @Autowired
    private BusinessSetService businessSetService;

    public static void main(String[] args) {

    }


    /**
     * 获取单条数据
     *
     * @param customer 左心房客户推送信息
     * @return 左心房客户推送信息
     */
    @Override
    public Customer get(Customer customer) {
        Customer dto = super.get(customer);
        return dto;
    }

    /**
     * 获取单条数据
     *
     * @param id 左心房客户推送信息id
     * @return 左心房客户推送信息
     */
    @Override
    public Customer get(String id) {
        Customer dto = super.get(id);
        return dto;
    }

    /**
     * 查询左心房客户推送信息列表
     *
     * @param customer 左心房客户推送信息
     * @return 左心房客户推送信息
     */
    @Override
    @DataScope(userAlias = "a", deptAlias = "a")
    public List<Customer> findList(Customer customer) {
        //return super.findList(customer);
        return addOtherInfo(mapper.findList(customer));
    }

    /**
     * 分页查询左心房客户推送信息列表
     *
     * @param customer 左心房客户推送信息
     * @return 左心房客户推送信息
     */
    @Override
    @DataScope(userAlias = "a", deptAlias = "a")
    public PageInfo<Customer> findPage(Customer customer) {
        //return super.findPage(customer);
        PageDomain page = customer.getPage();
        Integer pageNum = page.getPageNum();
        Integer pageSize = page.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            String orderBy = SqlUtil.escapeOrderBySql(page.getOrderBy());
            Boolean reasonable = page.getReasonable();
            PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
        }
        return new PageInfo(addOtherInfo(mapper.findList(customer)));
    }

    /**
     * 保存左心房客户推送信息
     *
     * @param customer
     * @return 结果
     */
    @Override
    public boolean save(Customer customer) {
        return super.save(customer);
    }

    /**
     * 删除左心房客户推送信息信息
     *
     * @param customer
     * @return 结果
     */
    @Override
    public boolean remove(Customer customer) {
        return super.remove(customer);
    }

    /**
     * 批量删除左心房客户推送信息
     *
     * @param ids 需要删除的左心房客户推送信息ID
     * @return 结果
     */
    @Transactional(readOnly = false)
    @Override
    public int deleteCustomerByIds(String[] ids) {
        return mapper.deleteCustomerByIds(ids);
    }

    /**
     * 获取最大编号
     *
     * @param customer 左心房客户推送信息
     * @return 结果
     */
    @Override
    public int findMaxSort(Customer customer) {
        return NumberUtils.nextOrder(mapper.findMaxSort(customer));
    }

    @Override
    public Customer findCustomerByphone(String phone) {
        Customer customer = new Customer();
        customer.setPhone(phone);
        List<Customer> customers = mapper.findList(customer);
        return customers.size() > 0 ? customers.get(0) : null;
    }

    @Override
    public boolean findCustomerByphone(Customer customer) {
        return mapper.findList(customer).size() > 0;
    }

    @Override
    public Customer findCustomerByphone(Customer customer, boolean is) {
        List<Customer> customers = mapper.findList(customer);
        return customers.size() > 0 ? customers.get(0) : null;
    }

    @Transactional(readOnly = false)
    @Override
    public Map savePushCustomer(Customer customer) {
        Map maps = new HashMap();
        Date date = new Date();
        try {
            String repMessage = "";
            if (StringUtils.isNotEmpty(customer.getLaiyuan()) && customer.getLaiyuan().equals("深圳佑人")) {
                customer.setRemark(customer.getRemark() + "/原城市：" + customer.getCityName());
                customer.setCityName("长沙");
            }
            //判断是否重名
            Customer res = findCustomerByphone(customer.getPhone());
            if (null != res && customer.getLaiyuan().equals(res.getLaiyuan())) {
                if ("欧乐".equals(res.getLaiyuan())) {
                    maps.put("code", "405");
                    maps.put("message", "同一客户信息重复/不入库");
                } else {
                    maps.put("code", "200");
                    maps.put("message", "同一客户信息重复/不入库");
                }
            } else {
                if (null != res) {
                    //相同业务相同手机号码标记为重复客户
                    customer.setIsRep(1);
                    maps.put("code", "200");
                    maps.put("message", "客户信息重复");
                    repMessage = customer.getLaiyuan() + "-(重复客户)-" + res.getLaiyuan();
                } else {
                    customer.setIsRep(0);
                    maps.put("code", "200");
                    maps.put("message", "推送成功");
                    repMessage = customer.getLaiyuan() + "(客户进线)";
                }
                customer.setId(UUID.randomUUID().toString());
                customer.setIsNewRecord();
                customer.setReceiveTime(new Date());
                customer.setCreateTime(new Date());
                customer.setIsDail(0l);
                customer.setType("1"); // 车贷
                customer.setLaiyuanType("1");// 广告客户
                customer.setStatus(CustomerEnum.DAI_FP.getStatus());
                customer.setUserId(null);
                customer.setUserName(null);
                customer.setDeptId(null);
                customer.setDeptName(null);
                super.save(customer);

                // 保存动态
                CustomerDongtai customerDongtai = new CustomerDongtai();
                customerDongtai.setCustomerId(customer.getId());
                customerDongtai.setType("1");
                customerDongtai.setContent(customer.getLaiyuan() + "-" + "广告客户进线" + repMessage);
                customerDongtaiService.save(customerDongtai);
            }
            // 保存推送记录
            PushCustomer pushCustomer = new PushCustomer();
            pushCustomer.setId(customer.getId());
            pushCustomer.setStatus("1");
            pushCustomer.setIsNewRecord();
            pushCustomer.setCusName(customer.getCusName());
            pushCustomer.setPhone(customer.getPhone());
            pushCustomer.setIsRep(customer.getIsRep());
            pushCustomer.setLaiyuan(customer.getLaiyuan());
            pushCustomer.setCityName(customer.getCityName());
            pushCustomer.setRemark(maps.get("message").toString());
            pushCustomer.setCreateTime(date);
            pushCustomerService.save(pushCustomer);
            // 保存动态
            CustomerDongtai customerDongtai = new CustomerDongtai();
            customerDongtai.setCustomerId(customer.getId());
            customerDongtai.setType(DongTaiTypeEnum.UPDATE_INFO.getStatus());
            ;
            customerDongtai.setContent(customer.getLaiyuan() + "-" + "广告客户进线" + repMessage);
            customerDongtaiService.save(customerDongtai);

            //保存线索成本记录
            XiansuoChengbenLog xiansuoChengbenLogParam = new XiansuoChengbenLog();
            xiansuoChengbenLogParam.setCityName(customer.getCityName());
            xiansuoChengbenLogParam.setLaiyuan(customer.getLaiyuan());
            xiansuoChengbenLogParam.setLaiyuanType("1");
            xiansuoChengbenLogParam.setCustomerId(customer.getId());
            xiansuoChengbenLogParam.setIsRep(customer.getIsRep());
            xiansuoChengbenLogParam.setIsSum(1);
            xiansuoChengbenLogService.saveByCityAndLaiyuan(xiansuoChengbenLogParam);

        } catch (Exception exception) {
            log.error("调用ApiPushCustomerController.savePushCustomer", JSONObject.toJSONString(customer));
            maps.put("code", "500");
            maps.put("message", exception.getMessage());
            maps.put("data", JSONObject.toJSONString(customer));
        }
        return maps;
    }

    /**
     * 分配客户给用户
     *
     * @param customer
     */
    @Override
    @Transactional(readOnly = false)
    public int shareCustomer(Customer customer, SysUser user) {
        int result = 0;
        if (null != user) {
            try {
                //开始分配
                customer = mapper.get(customer.getId());
                // 如果是不是重复客户
                if (0 == customer.getIsRep() || (1 == customer.getIsRep() && 1 == customer.getIsRepFen())) {
                    customer.setUserId(user.getUserId());
                    customer.setUserName(user.getName());
                    customer.setDeptId(user.getDeptId());
                    customer.setDeptName(user.getDeptName());
                    customer.setCompanyId(user.getCompanyId());
                    customer.setShareDate(new Date());
                    // 添加临时分配记录
                    TempShare tempShare = new TempShare();
                    tempShare.setSysUserId(user.getId());
                    tempShare.setCustomerId(customer.getId());
                    tempShare.setLaiyuan(customer.getLaiyuan());
                    tempShareService.save(tempShare);
                    // 修改分配次数
                    user.setDayShareCount(user.getDayShareCount() + 1);
                    userService.updateDayShareCount(user);
                    // 分配记录
                    ShareLog shareLog = new ShareLog();
                    shareLog.setCustomerId(customer.getId());
                    shareLog.setUserId(user.getUserId());
                    shareLog.setUserName(user.getName());
                    shareLog.setDeptId(user.getDeptId());
                    shareLog.setDeptName(user.getDeptName());
                    shareLog.setCompanyId(customer.getCusName());
                    shareLogService.save(shareLog);
                    customer.setStatus(CustomerEnum.MY_CUS.getStatus());
                    customer.setOwnType("0");
                    // 分配时间
                    customer.setLastTime(new Date());
                    // 如果是成交客户
                    if (1 == customer.getIsCj()) {
                        customer.setIsCj(0);
                        customer.setProgress("gjz");
                    }
                    if (super.save(customer) && CustomerEnum.MY_CUS.getStatus().equals(customer.getStatus())) {
                        //查询是否发送短信系统参数
                        String sendSmsIsSend = ConfigUtils.getConfigValueByKey("sendSms.isSend");
                        if (StringUtils.isNotNull(sendSmsIsSend) && "是".equals(sendSmsIsSend)) {
                            JSONObject jsonObject =
                                    JSONObject.parseObject(TencentSmsUtils.SmsSend(TencentSmsUtils.templateId_1,
                                            customer.getCusName(), user.getPhonenumber()));
                            SmsLog smsLog = new SmsLog();
                            smsLog.setPhone(user.getPhonenumber());
                            smsLog.setName(customer.getCusName());
                            smsLog.setCompanyId(user.getCompanyId());
                            smsLog.setUserId(user.getPhonenumber());
                            smsLog.setUserName(user.getName());
                            JSONArray jsonArray = jsonObject.getJSONArray("SendStatusSet");
                            for (int i = 0; i < jsonArray.size(); i++) {
                                smsLog.setStatus(jsonArray.getJSONObject(i).getString("Code"));
                                smsLog.setRemark(jsonArray.getJSONObject(i).getString("Message"));
                                smsLogService.save(smsLog);
                            }
                        }


                        CustomerDongtai customerDongtai = new CustomerDongtai();
                        customerDongtai.setCustomerId(customer.getId());
                        customerDongtai.setType(DongTaiTypeEnum.UPDATE_INFO.getStatus());
                        ;
                        customerDongtai.setContent("系统分配给-" + user.getName());
                        customerDongtaiService.save(customerDongtai);
                        JSONObject jsonObjectSocket = new JSONObject();
                        jsonObjectSocket.put("type", "fenpeiNewCus");
                        jsonObjectSocket.put("msg", "客户进线-" + customer.getCusName());
                        WebSocketUsers.sendMessageToUserByText(WebSocketUsers.TYPE_PC, user.getId(),
                                jsonObjectSocket.toJSONString());
                        messageInfoService.sendMsg(customer, MessageTypeEnum.JRXKH, jsonObjectSocket.getString("msg"));
                    }
                } else {
                    // 重复客户 添加协助信息
                    // 添加协助员工信息
                    CustomerXiezu customerXiezu = new CustomerXiezu();
                    String[] users = {user.getUserId()};
                    String[] usernames = {user.getName()};
                    customerXiezu.setXiezuUsers(users);
                    customerXiezu.setXiezuUserNames(usernames);
                    customerXiezu.setCustomerId(customer.getId());
                    customerXiezu.setUserName("系统分配");
                    for (String userid : customerXiezu.getXiezuUsers()) {
                        customerXiezu.setId(Md5Utils.hash(userid + customerXiezu.getCustomerId()));
                        customerXiezu.setXiezuUserId(userid);
                        if (null == customerXiezuService.get(Md5Utils.hash(userid + customerXiezu.getCustomerId()))) {
                            try {
                                customerXiezu.setIsNewRecord();
                                customerXiezuService.save(customerXiezu);
                            } catch (Exception e) {
                                log.info("协助人员添加失败" + e.getMessage());
                            }
                        } else {
                            customerXiezu.setCreateTime(new Date());
                            customerXiezuService.save(customerXiezu);
                        }
                    }
                    // 拼接数据
                    String userids = "", userNames = "";
                    for (int i = 0; i < customerXiezu.getXiezuUsers().length; i++) {
                        if (i == customerXiezu.getXiezuUsers().length - 1) {
                            userids += customerXiezu.getXiezuUsers()[i];
                            userNames += customerXiezu.getXiezuUserNames()[i];
                        } else {
                            userids += customerXiezu.getXiezuUsers()[i] + ",";
                            userNames += customerXiezu.getXiezuUserNames()[i] + ",";
                        }
                    }
                    // 客户动态分配

                    CustomerDongtai customerDongtai = new CustomerDongtai();
                    customerDongtai.setCustomerId(customerXiezu.getCustomerId());
                    customerDongtai.setType(DongTaiTypeEnum.UPDATE_INFO.getStatus());
                    ;
                    customerDongtai.setContent("自动分配协助(重复客户)-" + user.getName());
                    customerDongtaiService.save(customerDongtai);


                    // 协助记录
                    Xiezu xiezu = new Xiezu();
                    xiezu.setXiezuUserIds(userids);
                    xiezu.setXiezuUserNames(userNames);
                    xiezu.setCustomerId(customerXiezu.getCustomerId());
                    xiezu.setUserName("系统分配");
                    xiezuService.save(xiezu);

                    // 添加临时分配记录
                    TempShare tempShare = new TempShare();
                    tempShare.setSysUserId(user.getId());
                    tempShareService.save(tempShare);
                    // 修改分配次数
                    user.setDayShareCount(user.getDayShareCount() + 1);
                    userService.updateDayShareCount(user);
                    // 分配记录
                    ShareLog shareLog = new ShareLog();
                    shareLog.setCustomerId(customer.getId());
                    shareLog.setUserId(user.getUserId());
                    shareLog.setUserName(user.getName());
                    shareLog.setDeptId(user.getDeptId());
                    shareLog.setDeptName(user.getDeptName());
                    shareLog.setCompanyId(customer.getCusName());
                    shareLogService.save(shareLog);
                    customer.setStatus(CustomerEnum.MY_CUS.getStatus());
                    customer.setShareDate(new Date());
                    if (super.save(customer) && CustomerEnum.MY_CUS.getStatus().equals(customer.getStatus())) {
                        //查询是否发送短信系统参数
                        String sendSmsIsSend = ConfigUtils.getConfigValueByKey("sendSms.isSend");
                        if (StringUtils.isNotNull(sendSmsIsSend) && "是".equals(sendSmsIsSend)) {
                            // 发送协助短信
                            JSONObject jsonObject =
                                    JSONObject.parseObject(TencentSmsUtils.SmsSend(TencentSmsUtils.templateId_2,
                                            customer.getCusName(), user.getPhonenumber()));
                            SmsLog smsLog = new SmsLog();
                            smsLog.setPhone(user.getPhonenumber());
                            smsLog.setName(customer.getCusName());
                            smsLog.setCompanyId(user.getCompanyId());
                            smsLog.setUserId(user.getPhonenumber());
                            smsLog.setUserName(user.getName());
                            JSONArray jsonArray = jsonObject.getJSONArray("SendStatusSet");
                            for (int i = 0; i < jsonArray.size(); i++) {
                                smsLog.setStatus(jsonArray.getJSONObject(i).getString("Code"));
                                smsLog.setRemark(jsonArray.getJSONObject(i).getString("Message"));
                                smsLogService.save(smsLog);
                            }
                        }
                    }
                    JSONObject jsonObjectSocket = new JSONObject();
                    jsonObjectSocket.put("type", "xiezuCus");
                    jsonObjectSocket.put("msg", "您有新的协助客户进线-" + customer.getCusName());
                    WebSocketUsers.sendMessageToUserByText(WebSocketUsers.TYPE_PC, user.getId(),
                            jsonObjectSocket.toJSONString());
                    messageInfoService.sendMsg(customer, MessageTypeEnum.XZKH, jsonObjectSocket.getString("msg"));
                }
                PushCustomer pushCustomer = pushCustomerService.get(customer.getPushId());
                if (null != pushCustomer) {
                    // 修改推送的数据
                    pushCustomer.setUserId(user.getUserId());
                    pushCustomer.setUserName(user.getName());
                    pushCustomer.setDeptId(user.getDeptId());
                    pushCustomer.setDeptName(user.getDeptName());
                    pushCustomer.setCompanyId(user.getCompanyId());
                    pushCustomerService.save(pushCustomer);
                }
                // 修改线索成本记录
                xiansuoChengbenLogService.updateUserInfo(customer, user);

            } catch (Exception e) {
                customer.setStatus(CustomerEnum.FP_SHIBAI.getStatus());
                customer.setInfo(e.getMessage());
                super.save(customer);
            }

        } else {
            try {
                customer.setStatus(CustomerEnum.FP_SHIBAI.getStatus());
                customer.setInfo("没找到分配用户！");
                super.save(customer);
            } catch (Exception e) {
                log.error("没找到分配用户错误" + e.getMessage());
            }

        }
        result = 1;
        return result;
    }

    /**
     * 分配客户给用户
     *
     * @param customer
     */
    @Override
    @Transactional(readOnly = false)
    public int shareCustomerByRule(Customer customer, PushRuleUser user) {
        int result = 0;
        if (null != user) {
            try {
                //if (0 == customer.getIsRep() || (1 == customer.getIsRep() && 1 == customer.getIsRepFen())) {
                customer.setUserId(user.getUserId());
                customer.setUserName(user.getName());
                customer.setDeptId(user.getDeptId());
                customer.setDeptName(user.getDeptName());
                customer.setCompanyId(user.getCompanyId());
                customer.setShareDate(new Date());

                // 添加临时分配记录
                if (StringUtils.isNotNull(user.getId()) && StringUtils.isNotEmpty(user.getId())) {
                    TempShare tempShare = new TempShare();
                    tempShare.setSysUserId(user.getUserId());
                    tempShare.setRuleUserId(user.getId());
                    tempShare.setCustomerId(customer.getId());
                    tempShare.setLaiyuan(customer.getLaiyuan());
                    tempShareService.save(tempShare);
                    // 修改分配次数
                    if (null != user.getSharedCount()) {
                        user.setSharedCount(user.getSharedCount() + 1);
                    } else {
                        user.setSharedCount(1);
                    }

                    // 累计接单量
                    if (null != user.getTotalCount()) {
                        user.setTotalCount(user.getTotalCount() + 1);
                    } else {
                        user.setTotalCount(1);
                    }
                    pushRuleUserService.save(user);
                }


                // 分配记录
                ShareLog shareLog = new ShareLog();
                shareLog.setCustomerId(customer.getId());
                shareLog.setUserId(user.getUserId());
                shareLog.setUserName(user.getName());
                shareLog.setDeptId(user.getDeptId());
                shareLog.setDeptName(user.getDeptName());
                shareLog.setCompanyId(customer.getCusName());
                shareLog.setRuleId(user.getRuleId());
                shareLog.setRuleuserId(user.getId());
                shareLogService.save(shareLog);

                customer.setOwnType("0");
                // 分配时间
                customer.setLastTime(new Date());
                // 操作时间
                customer.setOperateTime(new Date());
                customer.setIsCj(0);
                customer.setProgress("gjz");
                boolean isSaved = super.save(customer);

                if (isSaved) {
                    result = 1;
                    CustomerDongtai customerDongtai = new CustomerDongtai();
                    customerDongtai.setCustomerId(customer.getId());
                    customerDongtai.setType(DongTaiTypeEnum.UPDATE_INFO.getStatus());
                    ;
                    customerDongtai.setContent("系统分配给-" + user.getName());
                    customerDongtaiService.save(customerDongtai);
                    JSONObject jsonObjectSocket = new JSONObject();
                    jsonObjectSocket.put("type", "fenpeiNewCus");
                    jsonObjectSocket.put("msg", "客户进线-" + customer.getCusName());
                    WebSocketUsers.sendMessageToUserByText(WebSocketUsers.TYPE_PC, user.getUserId(),
                            jsonObjectSocket.toJSONString());
                    messageInfoService.sendMsg(customer, MessageTypeEnum.JRXKH, jsonObjectSocket.getString("msg"));
                    // 记录我的接单
                    CustomerReceive customerReceive = new CustomerReceive();
                    customerReceive.setUserId(customer.getUserId());
                    customerReceive.setUserName(customer.getUserName());
                    customerReceive.setDeptId(customer.getDeptId());
                    customerReceive.setDeptName(customer.getDeptName());
                    customerReceive.setCompanyId(customer.getCompanyId());
                    customerReceive.setRemark("系统分配");
                    customerReceive.setShareTime(new Date());
                    customerReceive.setCustomerId(customer.getId());
                    customerReceive.setLaiyuan(customer.getLaiyuan());
                    customerReceiveService.save(customerReceive);
                }
                //}
                PushCustomer pushCustomer = pushCustomerService.get(customer.getPushId());
                if (null != pushCustomer) {
                    // 修改推送的数据
                    pushCustomer.setUserId(user.getUserId());
                    pushCustomer.setUserName(user.getName());
                    pushCustomer.setDeptId(user.getDeptId());
                    pushCustomer.setDeptName(user.getDeptName());
                    pushCustomer.setCompanyId(user.getCompanyId());
                    pushCustomerService.save(pushCustomer);
                }
                // 修改线索成本记录
                xiansuoChengbenLogService.updateUserInfo(customer, user);
            } catch (Exception e) {
                customer.setStatus(CustomerEnum.FP_SHIBAI.getStatus());
                customer.setInfo(e.getMessage());
                super.save(customer);
            }

        } else {
            try {
                customer.setStatus(CustomerEnum.FP_SHIBAI.getStatus());
                customer.setInfo("没找到分配用户！");
                super.save(customer);
            } catch (Exception e) {
                log.error("没找到分配用户错误" + e.getMessage());
            }

        }
        return result;
    }

    @Override
    @Transactional(readOnly = false)
    public int xieZhuCustomer(Customer customer, PushRuleUser user) {
        int result = 0;
        CustomerXiezu customerXiezu = new CustomerXiezu();
        String[] users = {user.getUserId()};
        String[] usernames = {user.getName()};
        customerXiezu.setXiezuUsers(users);
        customerXiezu.setXiezuUserNames(usernames);
        customerXiezu.setCustomerId(customer.getId());
        customerXiezu.setUserName("系统分配");
        for (String userid : customerXiezu.getXiezuUsers()) {
            customerXiezu.setId(Md5Utils.hash(userid + customerXiezu.getCustomerId()));
            customerXiezu.setXiezuUserId(userid);
            if (null == customerXiezuService.get(Md5Utils.hash(userid + customerXiezu.getCustomerId()))) {
                try {
                    customerXiezu.setIsNewRecord();
                    customerXiezuService.save(customerXiezu);
                } catch (Exception e) {
                    log.info("协助人员添加失败" + e.getMessage());
                }
            } else {
                customerXiezu.setCreateTime(new Date());
                customerXiezuService.save(customerXiezu);
            }
        }
        // 拼接数据
        String userids = "", userNames = "";
        for (int i = 0; i < customerXiezu.getXiezuUsers().length; i++) {
            if (i == customerXiezu.getXiezuUsers().length - 1) {
                userids += customerXiezu.getXiezuUsers()[i];
                userNames += customerXiezu.getXiezuUserNames()[i];
            } else {
                userids += customerXiezu.getXiezuUsers()[i] + ",";
                userNames += customerXiezu.getXiezuUserNames()[i] + ",";
            }
        }
        // 客户动态分配

        CustomerDongtai customerDongtai = new CustomerDongtai();
        customerDongtai.setCustomerId(customerXiezu.getCustomerId());
        customerDongtai.setType(DongTaiTypeEnum.UPDATE_INFO.getStatus());
        ;
        customerDongtai.setContent("系统自动添加协助(重复客户)-" + user.getName());
        customerDongtaiService.save(customerDongtai);


        // 协助记录
        Xiezu xiezu = new Xiezu();
        xiezu.setXiezuUserIds(userids);
        xiezu.setXiezuUserNames(userNames);
        xiezu.setCustomerId(customerXiezu.getCustomerId());
        xiezu.setUserName("系统分配");
        xiezuService.save(xiezu);


        // 分配记录
        ShareLog shareLog = new ShareLog();
        shareLog.setCustomerId(customer.getId());
        shareLog.setUserId(user.getUserId());
        shareLog.setUserName(user.getName());
        shareLog.setDeptId(user.getDeptId());
        shareLog.setDeptName(user.getDeptName());
        shareLog.setCompanyId(customer.getCusName());
        shareLog.setRuleId(user.getRuleId());
        shareLog.setRuleuserId(user.getId());
        shareLogService.save(shareLog);
        customer.setShareDate(new Date());

        boolean isSaved = super.save(customer);
        if (isSaved) {
            result = 1;
            // 发送给区域经理
            JSONObject jsonObjectSocket = new JSONObject();
            jsonObjectSocket.put("type", "xiezuCus");
            jsonObjectSocket.put("msg", "您有新的协助客户进线-" + customer.getCusName());
            WebSocketUsers.sendMessageToUserByText(WebSocketUsers.TYPE_PC, user.getId(),
                    jsonObjectSocket.toJSONString());


            // 更改为区域经理信息
            customer.setUserId(user.getUserId());
            customer.setUserName(user.getUserName());
            messageInfoService.sendMsg(customer, MessageTypeEnum.XZKH, jsonObjectSocket.getString("msg"));
        }
        return result;
    }

    @Override
    @Transactional(readOnly = false)
    public int batchShareCustomersToUserByIds(Customer customer, SysUser user) {
        return mapper.batchShareCustomersToUserByIds(customer, user);
    }

    @Override
    @Transactional(readOnly = false)
    public int updateStatusToWeiJie(List<Customer> list) {
        return mapper.updateStatusToWeiJie(list);
    }


    @Override
    @Transactional(readOnly = false)
    public int myShareCustomer(Customer customer, SysUser sysUser) {
        customer.setUserId(sysUser.getUserId());
        customer.setUserName(sysUser.getName());
        customer.setDeptId(sysUser.getDeptId());
        customer.setDeptName(sysUser.getDeptName());
        customer.setCompanyId(sysUser.getCompanyId());
        customer.setShareDate(new Date());
        customer.setStatus(CustomerEnum.MY_CUS.getStatus());
        customer.setOwnType("0");

        return mapper.update(customer);
    }

    /**
     * 根据客户查询可分配的用户
     *
     * @param customer
     * @return
     */
    @Override
    public SysUser findNextShareUser(Customer customer) {
        Map<String, Object> params = new HashMap<>();
        if (StringUtils.isEmpty(customer.getCityName())) {
            return null;
        }
        String[] areas = customer.getCityName().split("-");
        String area = "";
        if (areas.length == 2) {
            area = areas[1];
        } else {
            area = customer.getCityName();
        }
        params.put("cityName", area);
        params.put("laiyuan", customer.getLaiyuan());
        List<SysUser> sysUserList = iSysUserService.findShareUser(params);
        if (null == sysUserList || sysUserList.size() == 0) {
            //没有可分配的用户了  表示一轮已经分完了
            SysUser sysUser = new SysUser();
            sysUser.setCity(area);
            sysUser.setBusType(customer.getLaiyuan());
            List<SysUser> shareUserList = iSysUserService.findList(sysUser);
            tempShareService.deleteAll(shareUserList);
            //重新查询
            sysUserList = iSysUserService.findShareUser(params);
        }
        //如果查询到用户列表取第一个用户 如果没有用户了，返回空用户
        return sysUserList.size() > 0 ? sysUserList.get(0) : null;
    }

    /**
     * @return 查询一个为分配的用户
     */

    @Override
    public Customer findOne() {
        return mapper.findOne();
    }

    @Override
    public Customer findZkOne() {
        return mapper.findZkOne();
    }

    /**
     * @return 查询一个未接待分配的用户
     */
    @Override
    public Customer findWjOne() {
        return mapper.findWjOne();
    }

    @Transactional(readOnly = false)
    @Override
    public String importData(List<Customer> customers, String status) throws InterruptedException {
        if (StringUtils.isNull(customers) || customers.size() == 0) {
            throw new CustomException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        int reRep = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (Customer customer : customers) {
            try {
                if (StringUtils.isEmpty(customer.getCusName())) {
                    continue;
                }
                String pushId = UUID.randomUUID().toString();
                Integer isRep = 0;
                Date date = new Date();

                SysUser user = SecurityUtils.getLoginUser().getUser();
                String content = user.getName() + "-导入客户信息";
                //判断是否重名
                Customer res = findCustomerByphone(customer.getPhone());
                if (null != res) {
                    content += "(重复)";
                    isRep = 1;
                    this.InitCustomer(res, status, pushId, isRep);
                    customer.setId(res.getId());
                    customer.setUserId(user.getId());
                    customer.setUserName(user.getName());
                    customer.setDeptId(user.getDeptId());
                    customer.setDeptName(user.getDeptName());
                    customer.setCompanyId(user.getCompanyId());
                    mapper.update(res);
                    reRep++;
                } else {
                    customer.setId(UUID.randomUUID().toString());
                    this.InitCustomer(customer, status, pushId, isRep);
                    mapper.insert(customer);
                }

                CustomerDongtai customerDongtai = new CustomerDongtai();
                customerDongtai.setCustomerId(customer.getId());
                customerDongtai.setType(DongTaiTypeEnum.OPERATE.getStatus());
                customerDongtai.setContent(content);

                //保存成本记录
                XiansuoChengbenLog xiansuoChengbenLogParam = new XiansuoChengbenLog();
                xiansuoChengbenLogParam.setCityName(customer.getCityName());
                xiansuoChengbenLogParam.setLaiyuan(customer.getLaiyuan());
                xiansuoChengbenLogParam.setLaiyuanType("2");
                xiansuoChengbenLogParam.setCustomerId(customer.getId());
                xiansuoChengbenLogParam.setIsRep(isRep);
                xiansuoChengbenLogParam.setIsSum(1);


                // 记录我的接单
                CustomerReceive customerReceive = new CustomerReceive();
                customerReceive.setUserId(customer.getUserId());
                customerReceive.setUserName(customer.getUserName());
                customerReceive.setDeptId(customer.getDeptId());
                customerReceive.setDeptName(customer.getDeptName());
                customerReceive.setCompanyId(customer.getCompanyId());
                customerReceive.setRemark(content);
                customerReceive.setShareTime(new Date());
                customerReceive.setCustomerId(customer.getId());
                customerReceive.setLaiyuan(customer.getLaiyuan());
                // 保存推送记录
                PushCustomer pushCustomer = new PushCustomer();
                pushCustomer.setId(pushId);
                pushCustomer.setStatus("2");
                pushCustomer.setIsNewRecord();
                pushCustomer.setCusName(customer.getCusName());
                pushCustomer.setPhone(customer.getPhone());
                pushCustomer.setIsRep(isRep);
                pushCustomer.setLaiyuan(customer.getLaiyuan());
                pushCustomer.setCityName(customer.getCityName());
                pushCustomer.setRemark(content);
                pushCustomer.setCreateTime(date);

                customerDongtaiService.save(customerDongtai);
                xiansuoChengbenLogService.saveByCityAndLaiyuan(xiansuoChengbenLogParam);
                customerReceiveService.save(customerReceive);
                pushCustomerService.save(pushCustomer);
                successNum++;
            } catch (Exception e) {
                failureNum++;
                System.out.println(e.getMessage());
            }
            Thread.sleep(100L);
        }
        if (successNum > 0) {
            successMsg.append("操作成功：！成功： " + successNum + " 条，");
        }
        if (failureNum > 0) {
            successMsg.append("失败：" + failureNum + " 条， ");

        }
        if (reRep > 0) {
            successMsg.append("重复：" + reRep + " 条");

        }

        return successMsg.toString();
    }


    private void InitCustomer(Customer customer, String status, String pushId, Integer isRep) {
        if (StringUtils.isEmpty(status)) {
            customer.setStatus(CustomerEnum.DAI_FP.getStatus());
        } else {
            customer.setStatus(status);
        }
        customer.setUserId(SecurityUtils.getLoginUser().getUserId());
        customer.setUserName(SecurityUtils.getLoginUser().getUser().getName());
        customer.setDeptName(SecurityUtils.getLoginUser().getUser().getDeptName());
        customer.setDeptId(SecurityUtils.getLoginUser().getUser().getDeptId());
        customer.setReceiveTime(new Date());
        customer.setCompanyId(SecurityUtils.getLoginUser().getUser().getCompanyId());
        customer.setIp(SecurityUtils.getLoginUser().getUser().getLoginIp());
        customer.setCreateTime(new Date());
        customer.setLastTime(new Date());
        // 操作时间
        customer.setOperateTime(new Date());
        customer.setLaiyuanType("2");
        if (StringUtils.isEmpty(customer.getFuckCarNoTime())) {
            customer.setFuckCarNoTime(null);
        }
        customer.setOwnType("2");
        customer.setType("1");// 车贷
        customer.setIsRep(isRep);
        customer.setZkStatus("0");
        //去除空格
        if (null != customer.getPhone()) {
            customer.setPhone(customer.getPhone().trim());
        }
        customer.setPushId(pushId);
    }


    @Override
    @Transactional(readOnly = false)
    public Integer updateStatus(Customer customer) {
        return mapper.updateStatus(customer);
    }

    @Override
    public Customer findByPhone(Customer customer) {
        return mapper.findByPhone(customer);
    }

    @Override
    public List<Customer> findByNameOrPhone(Customer customer) {
        return mapper.findByNameOrPhone(customer);
    }

    @Override
    @DataScope(userAlias = "a", deptAlias = "a")
    public PageInfo<Customer> findListXieZu(Customer customer) {
        PageDomain page = customer.getPage();
        Integer pageNum = page.getPageNum();
        Integer pageSize = page.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            String orderBy = SqlUtil.escapeOrderBySql(page.getOrderBy());
            Boolean reasonable = page.getReasonable();
            PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
        }
        return new PageInfo(addOtherInfo(mapper.findListXieZu(customer)));
    }

    @Override
    public PageInfo<Customer> findgonghaiList(Customer customer) {
        PageDomain page = customer.getPage();
        Integer pageNum = page.getPageNum();
        Integer pageSize = page.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            String orderBy = SqlUtil.escapeOrderBySql(page.getOrderBy());
            Boolean reasonable = page.getReasonable();
            PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
        }
        return new PageInfo(addOtherInfo(mapper.findgonghaiList(customer)));
    }

    @Override
    public PageInfo<Customer> findMyList(Customer customer) {
        PageDomain page = customer.getPage();
        Integer pageNum = page.getPageNum();
        Integer pageSize = page.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            String orderBy = SqlUtil.escapeOrderBySql(page.getOrderBy());
            Boolean reasonable = page.getReasonable();
            PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
        }
        return new PageInfo(addOtherInfo(mapper.findMyList(customer)));
    }

    @Override
    @DataScope(userAlias = "a", deptAlias = "a")
    public PageInfo<Customer> findChengJiaoList(Customer customer) {
        PageDomain page = customer.getPage();
        if ("createTime".equals(page.getOrderByColumn())) {
            page.setOrderByColumn(null);
            page.setIsAsc(null);
        }
        Integer pageNum = page.getPageNum();
        Integer pageSize = page.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            String orderBy = SqlUtil.escapeOrderBySql(page.getOrderBy());
            Boolean reasonable = page.getReasonable();
            PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
        }
        return new PageInfo(addOtherInfo(mapper.findChengJiaoList(customer)));
    }


    @Override
    @DataScope(userAlias = "b", deptAlias = "b")
    public PageInfo<Customer> findXiansuoList(Customer customer) {
        PageDomain page = customer.getPage();
        Integer pageNum = page.getPageNum();
        Integer pageSize = page.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            String orderBy = SqlUtil.escapeOrderBySql(page.getOrderBy());
            Boolean reasonable = page.getReasonable();
            PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
        }
        List<Customer> customerList = addOtherInfo(mapper.findXiansuoList(customer));
        return new PageInfo(customerList);
    }


    @Override
    @DataScope(userAlias = "a", deptAlias = "a")
    public PageInfo<Customer> findDaigenjinList(Customer customer) {
        PageDomain page = customer.getPage();
        Integer pageNum = page.getPageNum();
        Integer pageSize = page.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            String orderBy = SqlUtil.escapeOrderBySql(page.getOrderBy());
            Boolean reasonable = page.getReasonable();
            PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
        }
        return new PageInfo(addOtherInfo(mapper.findDaigenjinList(customer)));
    }

    @Override
    @DataScope(userAlias = "a", deptAlias = "a")
    public PageInfo<Customer> findCustomerWithJoinList(Customer customer) {
        PageDomain page = customer.getPage();
        Integer pageNum = page.getPageNum();
        Integer pageSize = page.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            String orderBy = SqlUtil.escapeOrderBySql(page.getOrderBy());
            Boolean reasonable = page.getReasonable();
            PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
        }
        List<Customer> customerList = mapper.findCustomerWithJoinList(customer);
        return new PageInfo(customerList);
    }

    /***
     * 添加关联表信息
     * @param customerList
     * @return
     */
    private List<Customer> addOtherInfo(List<Customer> customerList) {
        if (null != customerList && !customerList.isEmpty()) {
            List<String> phoneList = customerList.stream().map(Customer::getPhone).collect(Collectors.toList());
            List<PushCustomer> pushCustomerList = pushCustomerService.findPushCustomerListByPhones(phoneList);
            Map<String, List<PushCustomer>> pushCustomerMap =
                    pushCustomerList.stream().collect(Collectors.groupingBy(PushCustomer::getPhone));

            List<String> customerIdList = customerList.stream().map(Customer::getId).collect(Collectors.toList());
            List<CustomerShadowInfo> customerShadowInfoList =
                    customerShadowInfoService.findShadowListByCustomerIds(customerIdList);
            Map<String, List<CustomerShadowInfo>> customerShadowInfoMap =
                    customerShadowInfoList.stream().collect(Collectors.groupingBy(CustomerShadowInfo::getCustomerId));
            for (Customer cus : customerList) {
                cus.setPushList(pushCustomerMap.get(cus.getPhone()));
                cus.setShadowList(customerShadowInfoMap.get(cus.getId()));
            }

//            List<CustomerTag> customerTagList = mapper.findTagListByCustomerIds(customerList);
//            Map<String, List<CustomerTag>> customerTagMap = customerTagList.stream().collect(Collectors.groupingBy
//            (CustomerTag::getCustomerId));
//            for (Customer cus : customerList) {
//                cus.setTagList(customerTagMap.get(cus.getId()));
//            }
        }

        return customerList;
    }

    /***
     * 添加动态表信息
     * @param customerList
     * @return
     */
    private List<Customer> addDongtaiInfo(List<Customer> customerList) {
        if (null != customerList && !customerList.isEmpty()) {
            List<CustomerDongtai> dongtaiList = mapper.findDongtaiListByCustomerIds(customerList);
            Map<String, List<CustomerDongtai>> customerDongtaiInfoMap =
                    dongtaiList.stream().collect(Collectors.groupingBy(CustomerDongtai::getCustomerId));
            for (Customer cus : customerList) {
                cus.setDongtaiList(customerDongtaiInfoMap.get(cus.getId()));
            }
        }
        return customerList;
    }

    /***
     * 添加进件表信息
     * @param customerList
     * @return
     */
    private List<Customer> addJinjianInfo(List<Customer> customerList) {
        if (null != customerList && !customerList.isEmpty()) {
            List<JinjianInfo> jinjianList = mapper.findJinjianListByCustomerIds(customerList);
            Map<String, List<JinjianInfo>> customerJinjianinfoMap =
                    jinjianList.stream().collect(Collectors.groupingBy(JinjianInfo::getCustomerId));
            for (Customer cus : customerList) {
                cus.setJinjianList(customerJinjianinfoMap.get(cus.getId()));
            }
        }
        return customerList;
    }

    @Override
    @Transactional(readOnly = false)
    public Integer updateMyStatus(Customer customer) {
        return mapper.updateMyStatus(customer);
    }

    @Override
    public List<CustomerExpertVo> findAllExportList() {
        return mapper.findAllExportList();
    }


    @Override
    @DataScope(userAlias = "a", deptAlias = "a")
    public List<YuanGongGongziVo> yuangonggongzitongji(Customer customer) {
        return mapper.yuangonggongzitongji(customer);
    }

    @Override
    public PageInfo<Customer> ysfindPage(Customer customer) {
        return super.findPage(customer);
    }

    @Override
    @Transactional(readOnly = false)
    public void updateStatusByJinJianStatus(JinjianInfo jinjianInfo) {
        List<Customer> customers = mapper.selectCustomerIdByJinJianStatus(jinjianInfo);
        Map<String, Object> params = new HashMap<>();
        params.put("list", customers);
        params.put("type", 3);
        String content = "";
        if ("1".equals(jinjianInfo.getIsFk())) {
            content = "已放款";
        }
        if ("1".equals(jinjianInfo.getStatus())) {
            content = "进件中";
        }
        if ("1".equals(jinjianInfo.getJinjianStatus())) {
            content = "待放款";
        }
        params.put("content", "系统操作-" + content + "-更新客户状态为成交客户");
        customerDongtaiService.insertBatch(params);
        mapper.updateStatusByJinJianStatus(jinjianInfo);
    }

    @Override
    @Transactional(readOnly = false)
    public void updateStatusToHongHai48(BusinessSetBo businessSetBo) {
        businessSetBo.setIsRemain(1);
        Map<String, Object> params = new HashMap<>();
        params.put("time", businessSetBo.getTime());
        params.put("type", 3);
        params.put("content", "系统操作-我的客户-" + businessSetBo.getTime() + "（小时）未跟进-更新客户状态为公海客户");
        mapper.insertDongtaiByStatusToHongHai48(params);
        businessSetBo.setDesc(params.get("content").toString());
        mapper.updateStatusToHongHai48(businessSetBo);
    }

    @Override
    @Transactional(readOnly = false)
    public void updateStatusToHongHai15(BusinessSetBo businessSetBo) {


        Map<String, Object> params = new HashMap<>();
        params.put("time", businessSetBo.getTime());
        params.put("type", 3);
        params.put("content", "系统操作-我的客户-跟进后" + businessSetBo.getTime() + "（天）未再跟进-更新客户状态为公海客户");
//        mapper.insertDongtaiByStatusToHongHai15(params);
//        businessSetBo.setDesc(params.get("content").toString());
//        mapper.updateStatusToHongHai15(businessSetBo);
        mapper.insertCustomerTestToHongHai15(params);
    }

//    @Override
//    @Transactional(readOnly = false)
//    public void updateStatusToHongHai3(BusinessSetBo businessSetBo) {
//
//        Map<String, Object> params = new HashMap<>();
//        params.put("time", businessSetBo.getTime());
//        params.put("type", 3);
//        params.put("content", "系统操作-我的客户-" + businessSetBo.getTime() + "（天）内，未连续跟进-更新客户状态为公海客户");
//        mapper.insertDongtaiByStatusToHongHai3(params);
//        businessSetBo.setDesc(params.get("content").toString());
//        mapper.updateStatusToHongHai3(businessSetBo);
//    }


    @Override
    @Transactional(readOnly = false)
    public void updateStatusToHongHai3(BusinessSetBo businessSetBo) {

        businessSetBo.setIsRemain(1);
        List<Customer> customerList = mapper.selectToHongHai3(businessSetBo);
        String[] ids = customerList.stream().map(Customer::getId).toArray(String[]::new);
        if (ids.length > 0) {
            String content = "系统操作-我的客户-" + businessSetBo.getTime() + "（天）内，未连续跟进-更新客户状态为公海客户";
            CustomerDongtai customerDongtai = new CustomerDongtai();
            customerDongtai.setType(DongTaiTypeEnum.SYSTEM.getStatus());
            ;
            customerDongtai.setContent(content);
            customerDongtai.preInsert();
            customerDongtaiService.insertBatchByCustomerIds(ids, customerDongtai);
            mapper.updateStatusToHongHai3(ids);
        }
    }


    @Override
    @Transactional(readOnly = false)
    public void updateStatusToHongHaiXianSuoChi(BusinessSetBo businessSetBo) {
        businessSetBo.setIsRemain(1);
        Map<String, Object> params = new HashMap<>();
        params.put("time", businessSetBo.getTime());
        params.put("type", 3);
        params.put("content", "系统操作-线索池-" + businessSetBo.getTime() + "（小时）未跟进-更新客户状态为公海客户");
        mapper.insertDongtaiByStatusToHongHaiXianSuoChi(params);
        businessSetBo.setDesc(params.get("content").toString());
        mapper.updateStatusToHongHaiXianSuoChi(businessSetBo);
    }

    @Override
    @Transactional(readOnly = false)
    public void updateStatusCancelRep(BusinessSetBo businessSetBo) {
        List<Customer> customers = mapper.selectIsRepToTime(businessSetBo);
        if (null != customers && !customers.isEmpty()) {
            Map<String, Object> params = new HashMap<>();
            params.put("list", customers);
            params.put("type", 3);
            params.put("content", "系统操作-" + businessSetBo.getTime() + "（天）重复标记-取消重复标记");
            customerDongtaiService.insertBatch(params);
            mapper.updateStatusCancelRep(businessSetBo);
        }
    }

    @Override
    @Transactional(readOnly = false)
    public void updateStatusCancelLock(BusinessSetBo businessSetBo) {
        List<Customer> customers = mapper.selectIsLockToTime(businessSetBo);
        if (null != customers && !customers.isEmpty()) {
            Map<String, Object> params = new HashMap<>();
            params.put("list", customers);
            params.put("type", 3);
            params.put("content", "系统操作-" + businessSetBo.getTime() + "（天）锁定客户-取消锁定");
            customerDongtaiService.insertBatch(params);
            mapper.updateStatusCancelLock(businessSetBo);
        }
    }

    /**
     * 查询已经锁客多少人
     */
    @Override
    public Integer findLocks(Customer customer) {
        return mapper.findLocks(customer);
    }

    /**
     * 锁客
     */
    @Override
    @Transactional(readOnly = false)
    public Integer lockCustomer(Customer customer) {
        return mapper.lockCustomer(customer);
    }

    @Override
    public List<Customer> selectToHongHai48(BusinessSetBo businessSetBo) {
        return mapper.selectToHongHai48(businessSetBo);
    }

    @Override
    public List<Customer> selectToHongHai3(BusinessSetBo businessSetBo) {
        return mapper.selectToHongHai3(businessSetBo);
    }

    @Override
    public List<Customer> selectToHongHai15(BusinessSetBo businessSetBo) {
        return mapper.selectToHongHai15(businessSetBo);
    }


    @Override
    public PageInfo<Customer> selectToHongHai15(Customer customer) {
        BusinessSet businessSet = businessSetService.get("index_set");
        if (null != businessSet) {
            // 客户被跟进后x(天)内，未再跟进，客户自动转入公海。锁住的客户除外
            if (null != businessSet.getIsTwoStatus() && 1 == businessSet.getIsTwoStatus()) {
                customer.setTime(businessSet.getContactTimesToGonghaiTwo());
            }
        }
        PageDomain page = customer.getPage();
        Integer pageNum = page.getPageNum();
        Integer pageSize = page.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            String orderBy = SqlUtil.escapeOrderBySql(page.getOrderBy());
            Boolean reasonable = page.getReasonable();
            PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
        }
        return new PageInfo(mapper.selectToHongHai15(customer));
    }


    @Override
    public List<Customer> selectIsRepToTime(BusinessSetBo businessSetBo) {
        return mapper.selectIsRepToTime(businessSetBo);
    }

    @Override
    public List<Customer> selectIsLockToTime(BusinessSetBo businessSetBo) {
        return mapper.selectIsLockToTime(businessSetBo);
    }

    @Override
    public List<Customer> selectCustomerIdByJinJianStatus(JinjianInfo jinjianInfo) {
        return mapper.selectCustomerIdByJinJianStatus(jinjianInfo);
    }

    @Override
    public List<Customer> findNotGen(BusinessSetBo businessSetBo) {
        return mapper.findNotGen(businessSetBo);
    }

    @Override
    @Transactional(readOnly = false)
    public Integer updateNotGen(Customer customer) {
        return mapper.updateNotGen(customer);
    }

    @Override
    public int deleteUsersToGongHai(String[] ids) {
        return mapper.deleteUsersToGongHai(ids);
    }

    @Override
    @Transactional(readOnly = false)
    public int insertRongXinKe(String orderNo) {
        String get_url = RongXiangKeAESUtil.HOST + "/crm-report/api/clue/readOrders";
        JSONObject params = new JSONObject();
        params.put("requestId", UUID.randomUUID());
        params.put("voucherCode", RongXiangKeAESUtil.VOUCHER_CODE);
        JSONObject dataJson = new JSONObject();
        dataJson.put("orderNo", orderNo);
        params.put("data", RongXiangKeAESUtil.encrypt(dataJson.toJSONString(), RongXiangKeAESUtil.KEY));
        JSONObject jsonObject = JSONObject.parseObject(HttpUtils.doPost(get_url, params));
        if (jsonObject.getInteger("code") != 200 || StringUtils.isEmpty(jsonObject.getString("data"))) {
            return 0;
        } else {
            String data = RongXiangKeAESUtil.decrypt(jsonObject.getString("data"), RongXiangKeAESUtil.KEY);
            JSONArray customerJsonList = JSONObject.parseArray(data);
            for (int i = 0; i < customerJsonList.size(); i++) {
                JSONObject customerJson = customerJsonList.getJSONObject(i);
                if (null != customerJson) {
                    Customer customer = new Customer();
                    customer.setLaiyuan("融享客");
                    boolean isNingbo = "宁波".equals(customerJson.getString("city"));
                    if (isNingbo) {
                        try {
                            String nbUrl = "http://crm.cyrcar.com/api/webApi/pushCustomer" +
                                    "/insertCustomerByRongXiangKeOrder";
                            JSONObject param = new JSONObject();
                            param.put("orderNo", orderNo);
                            String res = HttpUtils.doPost(nbUrl, param);
                            JSONObject resResult = JSONObject.parseObject(res);
                            if (StringUtils.isNotNull(resResult.getInteger("code")) && 200 == resResult.getInteger(
                                    "code")) {
                                return 1;
                            } else {
                                return 0;
                            }
                        } catch (Exception e) {
                            log.error("=====融享客推送宁波的数据异常======", e);
                        }
                    } else {
                        customer.setClueId(customerJson.getString("orderNo"));
                        customer.setCusCanal(customerJson.getString("source"));
                        customer.setCusBody(customerJson.getString("cstSource"));
                        customer.setCusName(customerJson.getString("name"));
                        customer.setAge(customerJson.getInteger("age"));
                        customer.setRemark(customerJson.getString("productName"));
                        customer.setPhone(customerJson.getString("phone"));
                        customer.setSex(customerJson.getInteger("sex") == 0 ? "女" : "男");
                        customer.setCityName(customerJson.getString("city"));
                        Optional.ofNullable(customerJson.getInteger("profession")).ifPresent(v -> {
                            switch (customerJson.getInteger("profession")) {
                                case 200:
                                    customer.setWorks("上班族");
                                    break;
                                case 300:
                                    customer.setWorks("自由职业");
                                    break;
                                case 400:
                                    customer.setWorks("企业主");
                                    break;
                                case 500:
                                    customer.setWorks("个体户");
                                    break;
                                case 800:
                                    customer.setWorks("公务员");
                                    break;
                                case 900:
                                    customer.setWorks("其他");
                                    break;
                            }

                        });

                        Optional.ofNullable(customerJson.getInteger("incomeMonth")).ifPresent(v -> {
                            customer.setIncomeMonth(customerJson.getInteger("incomeMonth") + "");
                        });


                        Optional.ofNullable(customerJson.getInteger("loanUse")).ifPresent(v -> {
                            switch (customerJson.getInteger("sesameScore")) {
                                case 0:
                                    customer.setSesameScore("无芝麻分");
                                    break;
                                case 10:
                                    customer.setSesameScore("600分以下");
                                    break;
                                case 20:
                                    customer.setSesameScore("600~650分");
                                    break;
                                case 30:
                                    customer.setSesameScore("650~700分");
                                    break;
                                case 40:
                                    customer.setSesameScore("700分以上");
                                    break;
                            }

                        });
                        Optional.ofNullable(customerJson.getString("loanMoney")).ifPresent(v -> {
                            customer.setAmount(customerJson.getString("loanMoney").substring(0,
                                    customerJson.getString("loanMoney").indexOf(".")) + "万元");
                        });

                        Optional.ofNullable(customerJson.getInteger("loanExpiresMonth")).ifPresent(v -> {
                            customer.setLoanExpiresMonth(customerJson.getInteger("loanExpiresMonth"));
                        });

                        Optional.ofNullable(customerJson.getInteger("loanUse")).ifPresent(v -> {
                            // 有值的处理逻辑
                            switch (customerJson.getInteger("loanUse")) {

                                case 10:
                                    customer.setLoanUse("消费贷");
                                    break;
                                case 20:
                                    customer.setLoanUse("结婚贷");
                                    break;
                                case 30:
                                    customer.setLoanUse("购房贷");
                                    break;
                                case 40:
                                    customer.setLoanUse("装修贷");
                                    break;
                                case 50:
                                    customer.setLoanUse("购车贷");
                                    break;
                                case 60:
                                    customer.setLoanUse("教育贷");
                                    break;
                                case 70:
                                    customer.setLoanUse("旅游贷");
                                    break;
                                case 80:
                                    customer.setLoanUse("医疗贷");
                                    break;
                                case 90:
                                    customer.setLoanUse("其他贷");
                                    break;
                            }
                        });

                        Optional.ofNullable(customerJson.getInteger("gjjScop")).ifPresent(v -> {

                            switch (customerJson.getInteger("gjjScop")) {
                                case 0:
                                    customer.setAccumulation("无公积金");
                                    break;
                                case 10:
                                    customer.setAccumulation("缴纳未满6个月");
                                    break;
                                case 20:
                                    customer.setAccumulation("缴纳6个月以上");
                                    break;
                            }
                        });


                        Optional.ofNullable(customerJson.getInteger("sbScop")).ifPresent(v -> {

                            switch (customerJson.getInteger("sbScop")) {
                                case 0:
                                    customer.setSocial("无社保");
                                    break;
                                case 10:
                                    customer.setSocial("缴纳未满6个月");
                                    break;
                                case 20:
                                    customer.setSocial("缴纳6个月以上");
                                    break;
                            }
                        });

                        Optional.ofNullable(customerJson.getInteger("house")).ifPresent(v -> {
                            switch (customerJson.getInteger("house")) {
                                case 0:
                                    customer.setHouseType("无房产");
                                    break;
                                case 10:
                                    customer.setHouseType("有房产，不抵押");
                                    break;
                                case 20:
                                    customer.setHouseType("有房产，可抵押");
                                    break;
                            }

                        });

                        Optional.ofNullable(customerJson.getInteger("car")).ifPresent(v -> {
                            switch (customerJson.getInteger("car")) {
                                case 0:
                                    customer.setCarStatus("无车产");
                                    break;
                                case 10:
                                    customer.setCarStatus("有车产，不抵押");
                                    break;
                                case 20:
                                    customer.setCarStatus("有车产，可抵押");
                                    break;
                            }

                        });

                        Optional.ofNullable(customerJson.getInteger("baodanScop")).ifPresent(v -> {

                            switch (customerJson.getInteger("baodanScop")) {
                                case 0:
                                    customer.setBaodanScop("无保险保单");
                                    break;
                                case 10:
                                    customer.setBaodanScop("缴纳未满1年");
                                    break;
                                case 20:
                                    customer.setBaodanScop("缴纳1年以上");
                                    break;
                            }
                        });
                        Optional.ofNullable(customerJson.getInteger("credit")).ifPresent(v -> {

                            switch (customerJson.getInteger("credit")) {
                                case 0:
                                    customer.setZx("无信用记录");
                                    break;
                                case 10:
                                    customer.setZx("信用良好无逾期");
                                    break;
                                case 20:
                                    customer.setZx("2年内逾期少于9次无90天以上逾期");
                                    break;
                                case 30:
                                    customer.setZx("2年内逾期少于9次有90天以上逾期");
                                    break;
                                case 40:
                                    customer.setZx("2年内逾期大于9次");
                                    break;
                                case 50:
                                    customer.setZx("半年内有60天以上逾期");
                                    break;
                                case 60:
                                    customer.setZx("半年内无60天以上逾期");
                                    break;
                            }
                        });
                        Optional.ofNullable(customerJson.getInteger("isLoans")).ifPresent(v -> {
                            switch (customerJson.getInteger("isLoans")) {
                                case 0:
                                    customer.setIsLoans("无微粒贷");
                                    break;
                                case 10:
                                    customer.setIsLoans("1~2千");
                                    break;
                                case 20:
                                    customer.setIsLoans("2~5千");
                                    break;
                                case 30:
                                    customer.setIsLoans("5千~1万");
                                    break;
                                case 40:
                                    customer.setIsLoans("1万以上");
                                    break;
                            }
                        });
                        Optional.ofNullable(customerJson.getInteger("manageYears")).ifPresent(v -> {
                            switch (customerJson.getInteger("manageYears")) {

                                case 10:
                                    customer.setManageYears("1年以下");
                                    break;
                                case 20:
                                    customer.setManageYears("1年至5年");
                                    break;
                                case 30:
                                    customer.setManageYears("5年以上");
                                    break;

                            }
                        });
                        Optional.ofNullable(customerJson.getString("turnover")).ifPresent(v -> {
                            customer.setTurnover(customerJson.getString("turnover"));
                        });
                        Optional.ofNullable(customerJson.getString("turnoverPublic")).ifPresent(v -> {
                            customer.setTurnoverPublic(customerJson.getString("turnoverPublic"));
                        });
                        Optional.ofNullable(customerJson.getInteger("workingYears")).ifPresent(v -> {
                            switch (customerJson.getInteger("workingYears")) {
                                case 10:
                                    customer.setWorkingYears("0~6个月");
                                    break;
                                case 20:
                                    customer.setWorkingYears("6~12个月");
                                    break;
                                case 30:
                                    customer.setWorkingYears("12个月以上");
                                    break;
                            }
                        });
                        Optional.ofNullable(customerJson.getInteger("registAddress")).ifPresent(v -> {
                            customer.setRegistAddress(customerJson.getInteger("registAddress") == 10 ? "本地" : "外地");
                        });
                        Optional.ofNullable(customerJson.getInteger("hasBusinessLicense")).ifPresent(v -> {
                            switch (customerJson.getInteger("hasBusinessLicense")) {
                                case 0:
                                    customer.setHasBusinessLicense("未注册");
                                    break;
                                case 10:
                                    customer.setHasBusinessLicense("注册1年以下");
                                    break;
                                case 20:
                                    customer.setHasBusinessLicense("注册1至5年");
                                    break;
                                case 30:
                                    customer.setHasBusinessLicense("注册5年以上");
                                    break;
                            }
                        });

                        Optional.ofNullable(customerJson.getInteger("creditCard")).ifPresent(v -> {
                            customer.setCreditCard(customerJson.getInteger("creditCard") == 0 ? "无信用卡" : "有信用卡");
                        });
                        Optional.ofNullable(customerJson.getString("apiSourceName")).ifPresent(v -> {
                            customer.setApiSourceName(customerJson.getString("apiSourceName"));
                        });
                        Optional.ofNullable(customerJson.getString("followUserName")).ifPresent(v -> {
                            customer.setFollowUserName(customerJson.getString("followUserName"));
                        });
                        Optional.ofNullable(customerJson.getString("brand")).ifPresent(v -> {
                            customer.setBrand(customerJson.getString("brand"));
                        });
                        customer.setClueId(orderNo);
                        Map map = savePushCustomer(customer);
                        if (map.get("code").equals("200")) {
                            String return_url = RongXiangKeAESUtil.HOST + "/crm-report/api/clue/readCallback";
                            params = new JSONObject();
                            params.put("voucherCode", RongXiangKeAESUtil.VOUCHER_CODE);
                            JSONObject data_return = new JSONObject();
                            List<String> orderNoList = new ArrayList<>();
                            orderNoList.add(orderNo);
                            data_return.put("orderNos", orderNoList);
                            data_return.put("status", 1);
                            params.put("data", RongXiangKeAESUtil.encrypt(data_return.toJSONString(),
                                    RongXiangKeAESUtil.KEY));
                            params.put("requestId", UUID.randomUUID());
                            JSONObject returnJson = JSONObject.parseObject(HttpUtils.doPost(return_url, params));
                            System.out.println(returnJson);
                        }
                    }

                }
            }
            return 1;
        }

    }

    @Override
    @Transactional(readOnly = false)
    public Integer updateIsHeart(Customer customer) {
        return mapper.updateIsHeart(customer);
    }

    /**
     * 1.唯一性的客户直接分发
     * 2.只记录撞库10个以内的
     * 3.三天内的，不重复激活（非唯一性匹配的）
     * 4.权限开放给分公司经理
     *
     * @param customer 查询到的客户
     * @param laiyuan  撞库来源
     * @param phone    撞库号码（一般是前面几位）
     * @param zkCount  撞库数量
     */
    @Override
    @Transactional(readOnly = false)
    public void updateStatusIfExistedAfterCheck(Customer customer, String laiyuan, String phone, Integer zkCount) {
        if (false) {
            try {
                //取系统参数-撞库条数以下分配
                String limitcountStr = ConfigUtils.getConfigValueByKey("zhuangku.limitcount.share");
                int limitcount = Convert.toInt(limitcountStr, 5);

                // 公海的分配
                boolean isGonghaiFen =
                        CustomerEnum.GONG_HAI.getStatus().equals(customer.getStatus()) && limitcount <= 5;
                // 电话11位；唯一性；公海客户 三种情况下分配
                boolean isFenPei = phone.length() == 11 || zkCount == 1 || isGonghaiFen;
                //取系统参数-撞库是否分配
                String isRepShare = ConfigUtils.getConfigValueByKey("pushCustomer.repShare");
                if (StringUtils.isNotNull(isRepShare) && "是".equals(isRepShare) && zkCount <= 10) {
                    //查询时间参数-撞库存储数据间隔 （小时）
                    String zhuangKuTimeStr = ConfigUtils.getConfigValueByKey("zhuangku.time");
                    double zhuangKuTime = Convert.toDouble(zhuangKuTimeStr, 0.0);
                    double hours = Double.MAX_VALUE;
                    //查最新撞库记录
                    ZhuangkuLog zkParam = new ZhuangkuLog();
                    zkParam.setCustomerId(customer.getId());
                    ZhuangkuLog zkOne = zhuangkuLogService.findOne(zkParam);
                    if (zkOne != null) {
                        // 将 Date 转换为 Instant
                        Instant receiveInstant = zkOne.getCreateTime().toInstant();
                        Instant nowInstant = Instant.now(); // 当前时间
                        // 计算时间间隔
                        Duration duration = Duration.between(receiveInstant, nowInstant);
                        // 获取总小时数（包括小数部分）
                        hours = duration.toMillis() / (1000.0 * 60 * 60); // 将毫秒转换为小时
                    }
                    if (hours >= zhuangKuTime) {
                        // 记录撞库日志
                        ZhuangkuLog zhuangkuLog = new ZhuangkuLog();
                        zhuangkuLog.setStatus(customer.getStatus());
                        zhuangkuLog.setIsNewRecord();
                        zhuangkuLog.setCustomerId(customer.getId());
                        zhuangkuLog.setLaiyuan(customer.getLaiyuan());
                        zhuangkuLog.setPhone(customer.getPhone());
                        zhuangkuLog.setOriginLaiyuan(laiyuan);
                        zhuangkuLog.setOriginPhone(phone);
                        zhuangkuLog.setOriginLength(phone.length());
                        zhuangkuLogService.save(zhuangkuLog);
                        //唯一匹配的直接分发
                        if (isFenPei) {
                            this.savePushCustomerZhuangku(customer, laiyuan);
                        }
                    }
                }
            } catch (Exception exception) {
                log.error("调用ApiPushCustomerController.updateStatusIfExistedAfterCheck",
                        JSONObject.toJSONString(exception));
            }
        }

    }


    @Transactional(readOnly = false)
    @Override
    public void savePushCustomerZhuangku(Customer customer, String newLaiyuan) {
        try {
            customer.setCityName(CityUtils.cityRules(customer.getCityName()));
            String pushId = UUID.randomUUID().toString();
            Date date = new Date();
            customer.setReceiveTime(date);
            if (StringUtils.isNotNull(customer.getRepCounts())) {
                customer.setRepCounts(customer.getRepCounts() + 1);
            } else {
                customer.setRepCounts(1);
            }
            customer.setShareCount(0);// 分配次数归零
            customer.setLaiyuan(newLaiyuan);
            customer.setCityName(customer.getCityName());
            customer.setIsRepFen(1);
            customer.setIsRep(1);
            customer.setPushId(pushId);
            customer.setLaiyuanType("1");// 广告客户
            customer.setZkStatus("1");
            // 客户不在黑名单 就重新分配 但是锁定的不分
            boolean isLock =
                    (null != customer.getStatus() && (customer.getStatus().equals(CustomerEnum.MY_CUS.getStatus()) || customer.getStatus().equals(CustomerEnum.YI_FP.getStatus())) && (null != customer.getIsLock() && customer.getIsLock() == 1));

            // 锁定的不分 但是要消息提醒
            if (isLock) {
                JSONObject jsonObjectSocket = new JSONObject();
                jsonObjectSocket.put("type", "fenpeiNewCus");
                jsonObjectSocket.put("msg", "您有撞库客户进线-" + customer.getCusName());
                WebSocketUsers.sendMessageToUserByText(WebSocketUsers.TYPE_PC, customer.getUserId(),
                        jsonObjectSocket.toJSONString());
                if (null != customer.getStatus() && customer.getStatus().equals(CustomerEnum.MY_CUS.getStatus())) {
                    messageInfoService.sendMsg(customer, MessageTypeEnum.ZKTX_MY, jsonObjectSocket.getString("msg"));
                } else if (null != customer.getStatus() && customer.getStatus().equals(CustomerEnum.YI_FP.getStatus())) {
                    messageInfoService.sendMsg(customer, MessageTypeEnum.ZKTX_XSC, jsonObjectSocket.getString("msg"));
                }

            }

            if (!customer.getStatus().equals(CustomerEnum.HEI_MINGDAN.getStatus()) && !isLock) {
                customer.setStatus(CustomerEnum.ZK_DAI_FP.getStatus());
            }
            boolean isSaved = this.save(customer);
            if (isSaved) {
                // 保存推送记录
                PushCustomer pushCustomer = new PushCustomer();
                pushCustomer.setId(pushId);
                pushCustomer.setStatus("3");
                pushCustomer.setIsNewRecord();
                pushCustomer.setCusName(customer.getCusName());
                pushCustomer.setPhone(customer.getPhone());
                pushCustomer.setIsRep(customer.getIsRep());
                pushCustomer.setLaiyuan(customer.getLaiyuan());
                pushCustomer.setCityName(customer.getCityName());
                pushCustomer.setRemark("客户信息重复1");
                pushCustomer.setCreateTime(date);
                pushCustomerService.save(pushCustomer);
                // 保存动态
                CustomerDongtai customerDongtai = new CustomerDongtai();
                customerDongtai.setCustomerId(customer.getId());
                customerDongtai.setType(DongTaiTypeEnum.UPDATE_INFO.getStatus());
                ;
                customerDongtai.setContent(customer.getLaiyuan() + "-" + "客户进线1");
                customerDongtaiService.save(customerDongtai);
                //保存线索成本记录
                XiansuoChengbenLog xiansuoChengbenLogParam = new XiansuoChengbenLog();
                xiansuoChengbenLogParam.setCityName(customer.getCityName());
                xiansuoChengbenLogParam.setLaiyuan(customer.getLaiyuan());
                xiansuoChengbenLogParam.setLaiyuanType(customer.getLaiyuanType());
                xiansuoChengbenLogParam.setCustomerId(customer.getId());
                xiansuoChengbenLogParam.setIsRep(1);
                xiansuoChengbenLogParam.setIsSum(0);// 撞库分发的不计算成本 不统计
                xiansuoChengbenLogParam.setIsZk(1);
                xiansuoChengbenLogService.saveByCityAndLaiyuan(xiansuoChengbenLogParam);
            }
        } catch (Exception exception) {
            log.error("调用ApiPushCustomerController.savePushCustomer", JSONObject.toJSONString(customer));
        }
    }


    @Override
    public Customer findGonghaiOne() {
        return mapper.findGonghaiOne();
    }

    @Override
    @DataScope(userAlias = "a", deptAlias = "a")
    public PageInfo<Customer> findZhuangKuList(Customer customer) {
        PageDomain page = customer.getPage();
        Integer pageNum = page.getPageNum();
        Integer pageSize = page.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            String orderBy = SqlUtil.escapeOrderBySql(page.getOrderBy());
            Boolean reasonable = page.getReasonable();
            PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
        }
        List<Customer> customerList = addOtherInfo(mapper.findZhuangKuList(customer));
        return new PageInfo(customerList);
    }

    /**
     * 查找我的接单列表
     *
     * @param customer
     * @return
     */
    @Override
    public PageInfo<Customer> findMyReceiveList(Customer customer) {
        PageDomain page = customer.getPage();
        Integer pageNum = page.getPageNum();
        Integer pageSize = page.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            String orderBy = SqlUtil.escapeOrderBySql(page.getOrderBy());
            Boolean reasonable = page.getReasonable();
            PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
        }
        return new PageInfo(reveiceAddOtherInfo(mapper.findMyReceiveList(customer)));
    }

    /***
     * 添加关联表信息
     * @param customerList
     * @return
     */
    private List<Customer> reveiceAddOtherInfo(List<Customer> customerList) {
        if (null != customerList && !customerList.isEmpty()) {
            String curUserId = SecurityUtils.getLoginUser().getUserId();

            List<String> phoneList = customerList.stream().map(Customer::getPhone).collect(Collectors.toList());
            List<PushCustomer> pushCustomerList = pushCustomerService.findPushCustomerListByPhones(phoneList);
            Map<String, List<PushCustomer>> pushCustomerMap =
                    pushCustomerList.stream().collect(Collectors.groupingBy(PushCustomer::getPhone));

            List<String> customerIdList = customerList.stream().map(Customer::getId).collect(Collectors.toList());
            List<CustomerShadowInfo> customerShadowInfoList =
                    customerShadowInfoService.findShadowListByCustomerIds(customerIdList);
            Map<String, List<CustomerShadowInfo>> customerShadowInfoMap =
                    customerShadowInfoList.stream().collect(Collectors.groupingBy(CustomerShadowInfo::getCustomerId));
            for (Customer cus : customerList) {
                cus.setPushList(pushCustomerMap.get(cus.getPhone()));
                cus.setShadowList(customerShadowInfoMap.get(cus.getId()));
                //我的接单里面 只能看到我的客户、公海客户、线索池、协助客户的跟进记录
                //我的客户
                boolean isMyCus =
                        (null != cus.getStatus() && cus.getStatus().equals(CustomerEnum.MY_CUS.getStatus()) && null != cus.getUserId() && cus.getUserId().equals(curUserId));
                //线索池客户
                boolean isMyXianSuoChi =
                        (null != cus.getStatus() && cus.getStatus().equals(CustomerEnum.YI_FP.getStatus()) && null != cus.getUserId() && cus.getUserId().equals(curUserId));
                //公海、
                boolean isPublicStatus =
                        null != cus.getStatus() && (cus.getStatus().equals(CustomerEnum.GONG_HAI.getStatus()));
                //协助客户
                CustomerXiezu customerXiezu = new CustomerXiezu();
                customerXiezu.setCustomerId(cus.getId());
                customerXiezu.setXiezuUserId(curUserId);
                List<CustomerXiezu> customerXiezuList = customerXiezuService.findList(customerXiezu);
                boolean isXieZhu = null != customerXiezuList && !customerXiezuList.isEmpty();
                if (isMyCus || isMyXianSuoChi || isPublicStatus || isXieZhu) {
                    cus.setIsAllowEdit(1);
                } else {
                    cus.setIsAllowEdit(0);
                }
            }
        }
        return customerList;
    }


    public List<Customer> findWjExceedTimeToShareList(BusinessSetBo businessSetBo) {
        businessSetBo.setIsRemain(1);
        return mapper.findWjExceedTimeToShareList(businessSetBo);
    }

    public List<Customer> findWjExceedCountToShareList(BusinessSetBo businessSetBo) {
        businessSetBo.setIsRemain(1);
        return mapper.findWjExceedCountToShareList(businessSetBo);
    }

    @Override
    @DataScope(userAlias = "a", deptAlias = "a")
    public PageInfo<Customer> findWillToGongHaiList(Customer customer) {
        List<Customer> list = new ArrayList<>();
        List<Customer> myCusList = new ArrayList<>();
        List<Customer> xiansuochiList = new ArrayList<>();
        List<Customer> unLianXuList = new ArrayList<>();
        // 读取配置参数
        BusinessSet businessSet = businessSetService.get("index_set");
        if (null != businessSet) {
            BusinessSetBo businessSetBo = null;
            // 客户被领取到我的客户后x(小时)内，未进行跟进，客户自动转入公海。
            if (null != businessSet.getIsCustomerToGonghai() && 1 == businessSet.getIsCustomerToGonghai()) {
                businessSetBo = new BusinessSetBo();
                businessSetBo.setTime(businessSet.getCustomerToGonghaiTimes());
                businessSetBo.setIsRemain(2);

                if (!SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
                    businessSetBo.setUserId(SecurityUtils.getUserId());
                }
                businessSetBo.setCusName(customer.getCusName());
                businessSetBo.setPhone(customer.getPhone());
                myCusList = mapper.selectToHongHai48(businessSetBo);
            }
            // 客户被领取到线索池后x(小时)内，未进行跟进，客户自动转入公海。
            if (null != businessSet.getIsGetXianSuoToGonghai() && 1 == businessSet.getIsGetXianSuoToGonghai()) {
                businessSetBo = new BusinessSetBo();
                businessSetBo.setTime(businessSet.getCustomerToGonghaiTimes());
                businessSetBo.setIsRemain(2);

                if (!SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
                    businessSetBo.setUserId(SecurityUtils.getUserId());
                }
                businessSetBo.setCusName(customer.getCusName());
                businessSetBo.setPhone(customer.getPhone());

                xiansuochiList = mapper.selectToHongHaiXianSuoChi(businessSetBo);
            }

            // 客户被领取前x天，未连续跟进，客户自动转入公海。
            if (null != businessSet.getIsOneStatus() && 1 == businessSet.getIsOneStatus()) {
                businessSetBo = new BusinessSetBo();
                businessSetBo.setTime(businessSet.getContactTimesToGonghaiOne());
                businessSetBo.setIsRemain(2);

                if (!SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
                    businessSetBo.setUserId(SecurityUtils.getUserId());
                }
                businessSetBo.setCusName(customer.getCusName());
                businessSetBo.setPhone(customer.getPhone());

                unLianXuList = mapper.selectToHongHai3(businessSetBo);
            }
        }

        list = Stream.concat(myCusList.stream(), xiansuochiList.stream())
                // 按id分组，对每个id取remainingSeconds最小的记录
                .collect(Collectors.toMap(Customer::getId,  // 以id作为key
                        cus -> cus,  // 保留整个Customer对象
                        // 当id冲突时，取remainingSeconds较小的记录
                        (c1, c2) -> c1.getRemainingSeconds() <= c2.getRemainingSeconds() ? c1 : c2)).values()  //
                // 获取去重后的Customer集合
                .stream()   // 转为流
                // 按remainingSeconds排序
                .sorted(Comparator.comparingInt(Customer::getRemainingSeconds)).collect(Collectors.toList());


        list = Stream.concat(list.stream(), unLianXuList.stream()).sorted(Comparator.comparingInt(Customer::getRemainingSeconds)).collect(Collectors.toList());
        ;


        PageDomain page = customer.getPage();
        Integer pageNum = page.getPageNum();
        Integer pageSize = page.getPageSize();
        // 计算总页数
        int totalCount = list.size();
        int totalPages = (int) Math.ceil((double) totalCount / pageSize);

        // 调整页码，确保不越界
        pageNum = Math.max(1, Math.min(pageNum, totalPages));

        // 计算起始和结束索引
        int fromIndex = (pageNum - 1) * pageSize;
        int toIndex = Math.min(fromIndex + pageSize, totalCount);

        // 返回分页数据
        PageInfo result = new PageInfo(list.subList(fromIndex, toIndex));
        result.setTotal(list.size());
        return result;

    }

    @Override
    @DataScope(userAlias = "a", deptAlias = "a")
    public PageInfo<Customer> findWeiJieWillToShareList(Customer customer) {
        List<Customer> mergedAndSortedList = null;
        List<Customer> wjExceedTimeList = new ArrayList<>();
        List<Customer> wjExceedCountList = new ArrayList<>();
        BusinessSetBo businessSetBo = new BusinessSetBo();
        BusinessSet businessSet = businessSetService.get("index_set");

        if (null != businessSet) {
            // 未接超时流转
            if (null != businessSet.getIsWjTimesOpen() && 1 == businessSet.getIsWjTimesOpen()) {
                businessSetBo = new BusinessSetBo();
                businessSetBo.setTime(businessSet.getWjTimes());
                businessSetBo.setIsRemain(2);
                if (!SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
                    businessSetBo.setUserId(SecurityUtils.getUserId());
                }
                businessSetBo.setCusName(customer.getCusName());
                businessSetBo.setPhone(customer.getPhone());

                wjExceedTimeList = mapper.findWjExceedTimeToShareList(businessSetBo);
            }


            // 未接超次流转
            if (null != businessSet.getIsWjCountsOpen() && 1 == businessSet.getIsWjCountsOpen()) {
                businessSetBo = new BusinessSetBo();
                businessSetBo.setTime(businessSet.getWjCounts());
                businessSetBo.setIsRemain(2);
                if (!SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
                    businessSetBo.setUserId(SecurityUtils.getUserId());
                }
                businessSetBo.setCusName(customer.getCusName());
                businessSetBo.setPhone(customer.getPhone());

                wjExceedCountList = mapper.findWjExceedCountToShareList(businessSetBo);
            }
            mergedAndSortedList = Stream.concat(wjExceedTimeList.stream(), wjExceedCountList.stream())
                    // 按id分组，对每个id取remainingSeconds最小的记录
                    .collect(Collectors.toMap(Customer::getId,  // 以id作为key
                            cus -> cus,  // 保留整个Customer对象
                            // 当id冲突时，取remainingSeconds较小的记录
                            (c1, c2) -> c1.getRemainingSeconds() <= c2.getRemainingSeconds() ? c1 : c2)).values()  //
                    // 获取去重后的Customer集合
                    .stream()   // 转为流
                    // 按remainingSeconds排序
                    .sorted(Comparator.comparingInt(Customer::getRemainingSeconds)).collect(Collectors.toList());

            PageDomain page = customer.getPage();
            Integer pageNum = page.getPageNum();
            Integer pageSize = page.getPageSize();
            // 计算总页数
            int totalCount = mergedAndSortedList.size();
            int totalPages = (int) Math.ceil((double) totalCount / pageSize);

            // 调整页码，确保不越界
            pageNum = Math.max(1, Math.min(pageNum, totalPages));

            // 计算起始和结束索引
            int fromIndex = (pageNum - 1) * pageSize;
            int toIndex = Math.min(fromIndex + pageSize, totalCount);

            // 返回分页数据
            PageInfo result = new PageInfo(mergedAndSortedList.subList(fromIndex, toIndex));
            result.setTotal(mergedAndSortedList.size());
            return result;
        }
        return new PageInfo(null);
    }
}
